package com.xls.boxlibrary.customcontrol;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;

import com.xls.boxlibrary.R;


/**
 * <pre>
 * Created by zhuguohui
 * Date: 2023/1/11
 * Time: 10:39
 * Desc:圆角图片
 * 使用radius属性定义四个角的圆角
 * 使用radius_top_left 定义左上角
 * 使用radius_top_right 定义右上角
 * 使用radius_bottom_left 定义左下角
 * 使用radius_bottom_right 定义右下角
 * 如果radius是宽高的一半。那么就是圆形图片了
 * </pre>
 */
public class RoundedImageView extends androidx.appcompat.widget.AppCompatImageView {

    private final float tlRadius;
    private final float trRadius;
    private final float brRadius;
    private final float blRadius;
    private Path path;

    public RoundedImageView(Context context) {
        this(context, null);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageView);

        float radius = array.getDimension(R.styleable.RoundedImageView_radius, 0);
        tlRadius = array.getDimension(R.styleable.RoundedImageView_radius_top_left, radius);
        trRadius = array.getDimension(R.styleable.RoundedImageView_radius_top_right, radius);
        brRadius = array.getDimension(R.styleable.RoundedImageView_radius_bottom_right, radius);
        blRadius = array.getDimension(R.styleable.RoundedImageView_radius_bottom_left, radius);
        setBackground(new ColorDrawable());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int save = canvas.save();
        canvas.clipPath(path, Region.Op.INTERSECT);
        super.onDraw(canvas);
        canvas.restoreToCount(save);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        path = new Path();
        RectF rectF = getRectF();
        float[] readius = {tlRadius, tlRadius, trRadius, trRadius, brRadius, brRadius, blRadius, blRadius};
        path.addRoundRect(rectF, readius, Path.Direction.CW);
    }

    private RectF getRectF() {
        Rect rect = new Rect();
        getDrawingRect(rect);
        RectF rectF = new RectF(rect);
        return rectF;
    }
}

